/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.builder.IncompleteElementException;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.parsing.PropertyParser;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Frank D. Martinez [mnesarco]
 */
public class XMLIncludeTransformer {

    private final Configuration configuration;
    private final MapperBuilderAssistant builderAssistant;

    public XMLIncludeTransformer(Configuration configuration, MapperBuilderAssistant builderAssistant) {
        this.configuration = configuration;
        this.builderAssistant = builderAssistant;
    }

    /**
     * 解析include节点
     *
     * @param source include节点
     */
    public void applyIncludes(Node source) {
        Properties variablesContext = new Properties();
        // 获取Mybatis全局配置
        Properties configurationVariables = configuration.getVariables();

        if (configurationVariables != null) {
            variablesContext.putAll(configurationVariables);
        }
        // 替换变量内容
        applyIncludes(source, variablesContext, false);
    }

    /**
     * 通过所有SQL片段递归应用包含。
     * Recursively apply includes through all SQL fragments.
     *
     * @param source           包含include节点的DOM树
     * @param variablesContext Mybatis的Settings配置
     */
    private void applyIncludes(Node source, final Properties variablesContext, boolean included) {
        if (source.getNodeName().equals("include")) {
            // 处理include 内容，对节点中包含的占位符进行替换解析

            // 获取include导入的代码片段，
            Node toInclude = findSqlFragment(getStringAttribute(source, "refid"), variablesContext);

            // 这一步是因为property子元素
            Properties toIncludeContext = getVariablesContext(source, variablesContext);
            // 递归处理处理include导入的代码片段中包含的include代码块(如果有的话)
            applyIncludes(toInclude, toIncludeContext, true);

            if (toInclude.getOwnerDocument() != source.getOwnerDocument()) {
                // 如果被引入的include代码块和引用方不属于同一文档，则动态添加include代码块的内容
                toInclude = source.getOwnerDocument().importNode(toInclude, true);
            }
            // 将include节点替换为真实的代码块
            source.getParentNode().replaceChild(toInclude, source);

            while (toInclude.hasChildNodes()) {
                // 将引入的SQL代码块中的内容插入引入的SQl代码块之前，这里其实是移除了SQL元素的声明，只保留了SQL内容。
                // 如果include节点还嵌套了其他的include节点，则将嵌套include插入所属父节点的第一个下级位置
                toInclude.getParentNode().insertBefore(toInclude.getFirstChild(), toInclude);
            }
            // 移除引入的Sql元素，只保留器内容
            toInclude.getParentNode().removeChild(toInclude);
            /*
                    示例：
                    <sql id="userColumns"> id,username,password </sql>
                    <select id="selectUsers" parameterType="int" resultType="hashmap">
                        select <include refid="userColumns"/>
                        from some_table
                        where id = #{id}
                    </select>
                    操作完成后:
                    <select id="selectUsers" parameterType="int" resultType="hashmap">
                        select id,username,password
                        from some_table
                        where id = #{id}
                    </select>
             */
        } else if (source.getNodeType() == Node.ELEMENT_NODE) {
            // 处理非Include内容
            if (included && !variablesContext.isEmpty()) {
                // 非根节点，且变量上下文不为空
                // 替换变量值
                // replace variables in attribute values
                NamedNodeMap attributes = source.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Node attr = attributes.item(i);
                    // 处理占位符内容
                    attr.setNodeValue(
                            PropertyParser.parse(attr.getNodeValue(), variablesContext)
                    );
                }
            }
            NodeList children = source.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                // 继续解析include节点.保证没有遗漏
                applyIncludes(children.item(i), variablesContext, included);
            }
        } else if (included && source.getNodeType() == Node.TEXT_NODE
                && !variablesContext.isEmpty()) {
            // 处理文本节点
            // 这里的文本内容是具体的SQL
            // 替换文本内的变量
            // replace variables in text node
            source.setNodeValue(PropertyParser.parse(source.getNodeValue(), variablesContext));
        }
    }

    /**
     * 寻址被引用的Sql代码块
     */
    private Node findSqlFragment(String refid, Properties variables) {
        // 获取include标签引用的id
        refid = PropertyParser.parse(refid, variables);
        // 将该ID转换为包含命名空间的唯一标志
        refid = builderAssistant.applyCurrentNamespace(refid, true);
        try {
            // 获取对应的代码片段
            XNode nodeToInclude = configuration.getSqlFragments().get(refid);
            // 返回对应节点的深度克隆(全新)
            return nodeToInclude.getNode().cloneNode(true);
        } catch (IllegalArgumentException e) {
            throw new IncompleteElementException("Could not find SQL statement to include with refid '" + refid + "'", e);
        }
    }

    private String getStringAttribute(Node node, String name) {
        return node.getAttributes().getNamedItem(name).getNodeValue();
    }

    /**
     * 获取include元素下的所有`property`元素定义，并转换为Properties对象，同时在处理的过程中会对占位符进行处理。
     * Read placeholders and their values from include node definition.
     *
     * @param node                      Include node instance include节点
     * @param inheritedVariablesContext Current context used for replace variables in new variables values 用于替换的变量值
     * @return variables context from include instance (no inherited values)
     */
    private Properties getVariablesContext(Node node, Properties inheritedVariablesContext) {
        Map<String, String> declaredProperties = null;
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node n = children.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                // 获取include嵌套的property元素的属性名称
                String name = getStringAttribute(n, "name");
                // Replace variables inside
                // 获取在${}占位符中的内容，如果能够不能够获取占位符对应的内容，则返回占位符本身。
                String value = PropertyParser.parse(getStringAttribute(n, "value"), inheritedVariablesContext);
                if (declaredProperties == null) {
                    declaredProperties = new HashMap<>();
                }
                // 保存占位符和值的对应关系
                if (declaredProperties.put(name, value) != null) {
                    throw new BuilderException("Variable " + name + " defined twice in the same include definition");
                }
            }
        }
        // 聚合所有的参数配置
        if (declaredProperties == null) {
            return inheritedVariablesContext;
        } else {
            Properties newProperties = new Properties();
            newProperties.putAll(inheritedVariablesContext);
            newProperties.putAll(declaredProperties);
            return newProperties;
        }
    }
}
